/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frm_Principal.java
 *
 * Created on 16/07/2011, 10:27:22
 */
package clientereligadora.formularios;

import clientereligadora.conexao.Conexao;
import clientereligadora.operacoes.Operacao;
import com.mysql.jdbc.Blob;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.sql.SQLException;
import java.text.Normalizer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Leandro Aquino
 */
public final class FormAlteraUsuario extends javax.swing.JFrame {

     
    Operacao operacao = new Operacao();
    FormLogin tela_login = new FormLogin();
    String nome;
    String login;
    String senha;
    String contraSenha;
    Date dataUltimAcesso;
    RenderedImage foto;
    FileInputStream fis;
    SimpleDateFormat dateFormatDB = new SimpleDateFormat("yyyy-MM-dd");
    Conexao conn;

    /**
     * Creates new form frm_Principal
     */
    public FormAlteraUsuario(Conexao conn) {
        initComponents();

        this.conn = conn;

        //carregaChebox();

        tela_login = new FormLogin();
        //FIXA APENAS LETRAS MAIUSCULAS NO NOME DO USUARIO
        // txt_nomeUsuario.setDocument(new MeuDocument());

        //LIMITA CARACTERES AO DIGITAR,NUMEROS E OUTRAS SENTENÇAS

        txt_nomeUsuario.setDocument(new formatNome());
        txt_login.setDocument(new tirarAcento());


        jPasswordField_senha.setDocument(new verificaSenha());
        jPasswordField_ConfirmaSenha.setDocument(new verificaSenha());

        //arrastando o texto com tecla Ctrl pressionada
        txt_nomeUsuario.setDragEnabled(true);




        setLocationRelativeTo(null); // CENTRALIZA PAGINA
        // operacao.getloginUsers(cbx_login);

        /*
         * TABELA USUARIOS
         */
        //txt_cod_user.setText("" + operacao.getLastUsers()); //converte
        //desabilita campo para edição
        txt_cod_user.setEnabled(false);
        txt_login.setEnabled(false);
        // resetUsuarios();
        tela_login.setVisible(false);



        // LAYOUT DE JOPTIONPANES
        Icon warning = new ImageIcon("C:\\cfgReligadora\\icons\\Warning.png");
        Icon ok = new ImageIcon("C:\\cfgReligadora\\icons\\OK.png");
        Icon erro = new ImageIcon("C:\\cfgReligadora\\icons\\Error.png");
        Icon info = new ImageIcon("C:\\cfgReligadora\\icons\\Infor.png");
        Icon questionIcon = new ImageIcon("C:\\cfgReligadora\\icons\\question.png");


        UIManager.put("OptionPane.yesButtonText", "Sim");
        UIManager.put("OptionPane.noButtonText", "Não");
        UIManager.put("OptionPane.cancelButtonText", "Cancelar");
        UIManager.put("OptionPane.informationIcon", info);
        UIManager.put("OptionPane.errorIcon", erro);
        UIManager.put("OptionPane.questionIcon", questionIcon);
        UIManager.put("OptionPane.warningIcon", warning);


        //LAYOUT CAIXA DE SELEÇÃO
        UIManager.put("FileChooser.openDialogTitleText", "Abrir");
        UIManager.put("FileChooser.lookInLabelText", "Procurar em");
        UIManager.put("FileChooser.saveInLabelText", "Salvar em");
        UIManager.put("FileChooser.openButtonText", "Abrir");
        UIManager.put("FileChooser.saveButtonText", "Salvar");
        UIManager.put("FileChooser.cancelButtonText", "Cancelar");
        UIManager.put("FileChooser.fileNameLabelText", "Nome do Arquivo");
        UIManager.put("FileChooser.filesOfTypeLabelText", "Tipo de Arquivo");
        UIManager.put("FileChooser.openButtonToolTipText", "Abrir o Arquivo Selecionado");
        UIManager.put("FileChooser.saveButtonToolTipText", "Salvar Arquivo Selecionado");
        UIManager.put("FileChooser.cancelButtonToolTipText", "Cancelar");
        UIManager.put("FileChooser.fileNameHeaderText", "Nome");
        UIManager.put("FileChooser.upFolderToolTipText", "Subir um Nível");
        UIManager.put("FileChooser.homeFolderToolTipText", "Área de Trabalho");
        UIManager.put("FileChooser.newFolderToolTipText", "Criar Nova Pasta");
        UIManager.put("FileChooser.listViewButtonToolTipText", "Lista");
        UIManager.put("FileChooser.newFolderButtonText", "Criar Nova Pasta");
        UIManager.put("FileChooser.renameFileButtonText", "Renomear");
        UIManager.put("FileChooser.deleteFileButtonText", "Deletar");
        UIManager.put("FileChooser.filterLabelText", "Tipo");
        UIManager.put("FileChooser.detailsViewButtonToolTipText", "Detalhes");
        UIManager.put("FileChooser.fileSizeHeaderText", "Tamanho");
        UIManager.put("FileChooser.fileDateHeaderText", "Data de Modificação");
        UIManager.put("FileChooser.acceptAllFileFilterText", "Todos os Arquivos");




    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPasswordField_senha = new javax.swing.JPasswordField();
        jPasswordField_ConfirmaSenha = new javax.swing.JPasswordField();
        jLabel6 = new javax.swing.JLabel();
        txt_cod_user = new javax.swing.JTextField();
        txt_nomeUsuario = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        imgUser = new javax.swing.JLabel();
        txt_login = new javax.swing.JTextField();
        cbx_login = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jcbx_todos = new javax.swing.JCheckBox();
        jcbx_incluir = new javax.swing.JCheckBox();
        jcbx_consultar = new javax.swing.JCheckBox();
        jcbx_alterar = new javax.swing.JCheckBox();
        jcbx_excluir = new javax.swing.JCheckBox();
        cbx_tipoUser = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        btn_cancelar1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        btn_cadastrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("CADASTRO DE USUARIOS");
        setResizable(false);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setAutoscrolls(true);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPasswordField_senha.setToolTipText("Senha");
        jPasswordField_senha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField_senhaActionPerformed(evt);
            }
        });
        jPasswordField_senha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField_senhaKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField_senhaKeyTyped(evt);
            }
        });
        jPanel1.add(jPasswordField_senha, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, 81, -1));

        jPasswordField_ConfirmaSenha.setToolTipText("Confirmar Senha");
        jPasswordField_ConfirmaSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField_ConfirmaSenhaActionPerformed(evt);
            }
        });
        jPasswordField_ConfirmaSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField_ConfirmaSenhaKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jPasswordField_ConfirmaSenhaKeyTyped(evt);
            }
        });
        jPanel1.add(jPasswordField_ConfirmaSenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 130, 82, -1));

        jLabel6.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel6.setText("Nome:");
        jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 60, -1, -1));

        txt_cod_user.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        txt_cod_user.setToolTipText("Código do Usuario");
        txt_cod_user.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_cod_userActionPerformed(evt);
            }
        });
        jPanel1.add(txt_cod_user, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 80, 46, -1));

        txt_nomeUsuario.setToolTipText("Nome do Usuário");
        txt_nomeUsuario.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txt_nomeUsuarioCaretUpdate(evt);
            }
        });
        txt_nomeUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_nomeUsuarioActionPerformed(evt);
            }
        });
        txt_nomeUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_nomeUsuarioKeyPressed(evt);
            }
        });
        jPanel1.add(txt_nomeUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 80, 170, -1));

        jLabel10.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel10.setText("Confirmar Senha:");
        jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 110, -1, -1));

        jLabel5.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel5.setText("Cod:");
        jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, -1, -1));

        jLabel2.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel2.setText("Senha:");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 110, -1, -1));

        imgUser.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        imgUser.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imgUser.setToolTipText("Adicionar uma imagem");
        imgUser.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        imgUser.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        imgUser.setFocusable(false);
        imgUser.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        imgUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                imgUserMouseClicked(evt);
            }
        });
        jPanel1.add(imgUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 20, 107, 130));

        txt_login.setToolTipText("Nome do Usuário");
        txt_login.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_loginKeyPressed(evt);
            }
        });
        jPanel1.add(txt_login, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 80, 90, -1));

        cbx_login.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        cbx_login.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-" }));
        cbx_login.setToolTipText("Perfil do Usuário");
        jPanel1.add(cbx_login, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 31, 112, -1));

        jLabel8.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel8.setText("Usuário:");
        jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        jLabel12.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        jLabel12.setText("Login:");
        jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 60, -1, -1));

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Permissões", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 0, 10), java.awt.Color.blue)); // NOI18N
        jPanel2.setForeground(new java.awt.Color(0, 0, 50));

        jcbx_todos.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_todos.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_todos.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_todos.setText("Todos");

        jcbx_incluir.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_incluir.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_incluir.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_incluir.setText("Incluir");
        jcbx_incluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbx_incluirActionPerformed(evt);
            }
        });

        jcbx_consultar.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_consultar.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_consultar.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_consultar.setText("Consultar");

        jcbx_alterar.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_alterar.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_alterar.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_alterar.setText("Alterar");

        jcbx_excluir.setBackground(new java.awt.Color(255, 255, 255));
        jcbx_excluir.setFont(new java.awt.Font("Arial", 0, 9)); // NOI18N
        jcbx_excluir.setForeground(new java.awt.Color(0, 0, 50));
        jcbx_excluir.setText("Excluir");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jcbx_incluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_alterar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_excluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_consultar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jcbx_todos)
                .addContainerGap(28, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbx_incluir)
                    .addComponent(jcbx_alterar)
                    .addComponent(jcbx_excluir)
                    .addComponent(jcbx_consultar)
                    .addComponent(jcbx_todos))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, -1, -1));

        cbx_tipoUser.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
        cbx_tipoUser.setForeground(new java.awt.Color(0, 0, 50));
        cbx_tipoUser.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-", "Administrador", "Usuarios" }));
        cbx_tipoUser.setToolTipText("Perfil do Usuário");
        cbx_tipoUser.addMouseWheelListener(new java.awt.event.MouseWheelListener() {
            public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
                cbx_tipoUserMouseWheelMoved(evt);
            }
        });
        cbx_tipoUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbx_tipoUserActionPerformed(evt);
            }
        });
        jPanel1.add(cbx_tipoUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 130, 120, -1));

        jLabel3.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 0, 50));
        jLabel3.setText("Permissão:");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 110, -1, -1));
        jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 130, 20, 20));

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jButton1.setForeground(new java.awt.Color(0, 0, 50));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/3.png"))); // NOI18N
        jButton1.setText("Foto");
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jButton1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 170, 110, -1));

        btn_cancelar1.setBackground(new java.awt.Color(255, 255, 255));
        btn_cancelar1.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        btn_cancelar1.setForeground(new java.awt.Color(0, 0, 50));
        btn_cancelar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/52.png"))); // NOI18N
        btn_cancelar1.setMnemonic('n');
        btn_cancelar1.setText("Cancelar");
        btn_cancelar1.setToolTipText("Cadastrar Usuario");
        btn_cancelar1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btn_cancelar1.setIconTextGap(5);
        btn_cancelar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cancelar1ActionPerformed(evt);
            }
        });
        jPanel1.add(btn_cancelar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 270, -1, -1));

        jButton2.setBackground(new java.awt.Color(255, 255, 255));
        jButton2.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        jButton2.setForeground(new java.awt.Color(0, 0, 50));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/39.png"))); // NOI18N
        jButton2.setMnemonic('A');
        jButton2.setText("Alterar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 270, 90, -1));

        btn_cadastrar.setBackground(new java.awt.Color(255, 255, 255));
        btn_cadastrar.setFont(new java.awt.Font("Arial", 0, 10)); // NOI18N
        btn_cadastrar.setForeground(new java.awt.Color(0, 0, 50));
        btn_cadastrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/36.png"))); // NOI18N
        btn_cadastrar.setMnemonic('C');
        btn_cadastrar.setText("Salva");
        btn_cadastrar.setToolTipText("Cadastrar Usuario");
        btn_cadastrar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btn_cadastrar.setIconTextGap(5);
        btn_cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cadastrarActionPerformed(evt);
            }
        });
        jPanel1.add(btn_cadastrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 270, 90, -1));

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 480, 320));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void imgUserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_imgUserMouseClicked
        try {
            carregaImagemUser();
        } catch (IOException ex) {
            Logger.getLogger(FormAlteraUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_imgUserMouseClicked

    private void jPasswordField_senhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_senhaKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField_senhaKeyTyped

    private void jPasswordField_ConfirmaSenhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_ConfirmaSenhaKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField_ConfirmaSenhaKeyTyped

    private void jPasswordField_senhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField_senhaActionPerformed
    }//GEN-LAST:event_jPasswordField_senhaActionPerformed

    private void jPasswordField_ConfirmaSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField_ConfirmaSenhaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField_ConfirmaSenhaActionPerformed

    private void txt_nomeUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_nomeUsuarioActionPerformed
    }//GEN-LAST:event_txt_nomeUsuarioActionPerformed

    private void txt_nomeUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_nomeUsuarioKeyPressed
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {

            if ((txt_nomeUsuario.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
                JOptionPane.showMessageDialog(this, "CAMPO 'NOME DO USUARIO' EM BRANCO \n"
                        + "VERIFIQUE OS CAMPOS DIGITADOS ");

                txt_nomeUsuario.setText("");
                txt_nomeUsuario.requestFocus();

            } else {
                //  txt_login.setEnabled(true);
                ((JTextField) (evt.getSource())).transferFocus();
            }
        }        // TODO add your handling code here:
    }//GEN-LAST:event_txt_nomeUsuarioKeyPressed

    private void jPasswordField_senhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_senhaKeyPressed

        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {

            if ((jPasswordField_senha.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
                JOptionPane.showMessageDialog(this, "CAMPO 'SENHA' EM BRANCO! \n"
                        + "VERIFIQUE OS CAMPOS DIGITADOS ");

                jPasswordField_senha.requestFocus();

            } else {
                ((JTextField) (evt.getSource())).transferFocus();
            }
        }
    }//GEN-LAST:event_jPasswordField_senhaKeyPressed

    private void jPasswordField_ConfirmaSenhaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField_ConfirmaSenhaKeyPressed
        int key = evt.getKeyCode();

        //((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Tab))
        //if ((key == KeyEvent.VK_ENTER) &&(key == KeyEvent.VK_TAB) ){
        if (key == KeyEvent.VK_ENTER) {
            if ((jPasswordField_ConfirmaSenha.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
                JOptionPane.showMessageDialog(this, "CAMPO 'CONFIRMA SENHA' EM BRANCO! \n"
                        + "VERIFIQUE OS CAMPOS DIGITADOS ");
                jPasswordField_ConfirmaSenha.requestFocus();
            }
            if ((jPasswordField_senha.getText() == null ? (jPasswordField_ConfirmaSenha.getText()) == null : jPasswordField_senha.getText().equals(jPasswordField_ConfirmaSenha.getText()))) {

                ((JTextField) (evt.getSource())).transferFocus();

            } else {
                JOptionPane.showMessageDialog(this, "SENHA NAO CONFERE! \n"
                        + "VERIFIQUE OS CAMPOS SELECIONADOS ! ");

                jPasswordField_senha.setText("");
                jPasswordField_ConfirmaSenha.setText("");
                jPasswordField_senha.requestFocus();
            }
        }
    }//GEN-LAST:event_jPasswordField_ConfirmaSenhaKeyPressed

    private void txt_nomeUsuarioCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txt_nomeUsuarioCaretUpdate
        if ((txt_nomeUsuario.getText().equals(""))) {
            txt_login.setEnabled(false);

        } else {
            txt_login.setEnabled(true);
        }
    }//GEN-LAST:event_txt_nomeUsuarioCaretUpdate

    private void txt_cod_userActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_cod_userActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txt_cod_userActionPerformed

    private void txt_loginKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_loginKeyPressed
        String login = txt_login.getText();
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            if ((txt_login.getText().equals(""))) {

                JOptionPane.showMessageDialog(this, "PREENCHA OS CAMPOS CORRETAMENTE", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
                JOptionPane.showMessageDialog(this, "CAMPO 'LOGIN' EM BRANCO! \n"
                        + "VERIFIQUE OS CAMPOS DIGITADOS ");

                txt_login.requestFocus();

            } //
//            else if (login == null ? operacao.verificaLogin(login) == null : login.equals(operacao.verificaLogin(login))) {
//
//                JOptionPane.showMessageDialog(this, "ATENÇÃO, VERIFIQUE O LOGIN DIGITADO", "ATENÇÃO", JOptionPane.WARNING_MESSAGE);
//                JOptionPane.showMessageDialog(this, "EXISTE UM USUARIO COM MESMO LOGIN CADASTRADO NO SISTEMA! \n"
//                        + "INSIRA UM NOVO USUARIO");
//
//                txt_login.setText("");
//                txt_login.requestFocus();
//
//            }else
//                ((JTextField) (evt.getSource())).transferFocus();
//        }
        }
    }//GEN-LAST:event_txt_loginKeyPressed

    private void jcbx_incluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbx_incluirActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jcbx_incluirActionPerformed

    private void cbx_tipoUserMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_cbx_tipoUserMouseWheelMoved
        // TODO add your handling code here:

        int count = cbx_tipoUser.getItemCount();

        if (count < 2) {
            return;
        }

        int index = cbx_tipoUser.getSelectedIndex();
        if (index == -1) {
            index = 0;
        }

        // VOLTA O ITEM ANTERIOR
        if (evt.getWheelRotation() < 0) {
            if (index > 0) {
                cbx_tipoUser.setSelectedIndex(index - 1);
            }
        } // PULA O PROXIMO ITEM
        else {
            if (index < count - 1) {
                cbx_tipoUser.setSelectedIndex(index + 1);
            }
        }
        evt.consume();
    }//GEN-LAST:event_cbx_tipoUserMouseWheelMoved

    private void cbx_tipoUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbx_tipoUserActionPerformed

        String permissao = cbx_tipoUser.getSelectedItem().toString();

        if (permissao.equals("Administrador")) {
            bloqueiaChecbox();

        } else if (permissao.equals("Usuarios")) {

            liberaChebox();
        } else {
            JOptionPane.showMessageDialog(this, "PERFIL SELECIONADO INCORRETO \n"
                    + "VERIFIQUE OS CAMPOS SELECIONADOS ! ");
        }
    }//GEN-LAST:event_cbx_tipoUserActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            carregaImagemUser();

        } catch (IOException ex) {
            Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btn_cancelar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelar1ActionPerformed
        try {
            capturaImagem(12);
        } catch (IOException ex) {
            Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }

 }//GEN-LAST:event_btn_cancelar1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        FormAlteraUsuario updateUser = new FormAlteraUsuario(conn);
        updateUser.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btn_cadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cadastrarActionPerformed


        dataUltimAcesso = new Date();

        String dat = dateFormatDB.format(dataUltimAcesso);

        nome = txt_nomeUsuario.getText().toString().toUpperCase();

        login = txt_login.getText().toString();

        senha = jPasswordField_senha.getText();

        contraSenha = jPasswordField_ConfirmaSenha.getText();

        if (nome.equals("") || nome == null) {
            JOptionPane.showMessageDialog(null, "CAMPO NOME EM BRANCO");
        } else if (login.equals("") || login == null) {
            JOptionPane.showMessageDialog(null, "CAMPO LOGIN EM BRANCO");
        } else if (senha.equals("") || senha == null) {
            JOptionPane.showMessageDialog(null, "CAMPO SENHA EM BRANCO");
        } else if (contraSenha.equals("") || contraSenha == null) {
            JOptionPane.showMessageDialog(null, "CAMPO CONFIRMAR SENHA EM BRANCO");
        } else {
            try {
                //  inserir.inserirUsuario(nome, login, senha, "ATVO", dataUltimAcesso, foto);
                insereImagem(login, foto, fis);
            } catch (IOException ex) {
                Logger.getLogger(FormCadastroUsuario.class.getName()).log(Level.SEVERE, null, ex);
            }
            resetUsuarios();
        }

    }//GEN-LAST:event_btn_cadastrarActionPerformed

    public void liberaChebox() {


        for (Component cp : jPanel2.getComponents()) {
            cp.setEnabled(true);

        }
        jcbx_alterar.setSelected(false);
        jcbx_excluir.setSelected(false);
        jcbx_consultar.setSelected(false);
        jcbx_incluir.setSelected(false);
        jcbx_todos.setSelected(false);

    }

    public void carregaChebox() {


        for (Component cp : jPanel2.getComponents()) {
            cp.setEnabled(false);

        }
        jcbx_alterar.setSelected(false);
        jcbx_excluir.setSelected(false);
        jcbx_consultar.setSelected(false);
        jcbx_incluir.setSelected(false);
        jcbx_todos.setSelected(false);


    }

    public void bloqueiaChecbox() {
        for (Component cp : jPanel2.getComponents()) {
            cp.setEnabled(false);

        }

        jcbx_alterar.setSelected(true);
        jcbx_excluir.setSelected(true);
        jcbx_consultar.setSelected(true);
        jcbx_incluir.setSelected(true);
        jcbx_todos.setSelected(true);


    }

    private void resetUsuarios() {

        txt_login.setText("");
        txt_nomeUsuario.setText("");
        jPasswordField_senha.setText("");
        jPasswordField_ConfirmaSenha.setText("");
        carregaChebox();

    }

    public void carregaImagemUser() throws IOException {

        String arq = null;

        JFileChooser arquivo = new JFileChooser();

        JFileChooser fc = new JFileChooser();
// int = returnVal fc.showDialog (FileChooserDemo2.this, "Attach");
        arquivo.setCurrentDirectory(new File("./src/imagens"));

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Arquivos de Imagens (.jpg/.png)", "jpg", "png");

        //ADICIONA A EXTENSAO NA TELA
        arquivo.addChoosableFileFilter(filter);

        //NAO LISTA TODOS OS ARQUIVOS
        arquivo.setAcceptAllFileFilterUsed(false);

        //Adiciona a janela de preview(visualizaÃ§Ã£o de imagem).
        arquivo.setAccessory(new ImagePreview(arquivo));
        //  this.JFileChooser.setCurrentDirectory(new File("C:/Sistemas/GerenteProjeto/src/gerenteprojeto/icons"));

        int result = arquivo.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {

            arq = arquivo.getSelectedFile().getPath();
            // imgUser.setIcon(new ImageIcon(arq.getAbsolutePath()));

            File imagem = arquivo.getSelectedFile();//arquivo
            String cam = imagem.getAbsolutePath();
            BufferedImage bi = ImageIO.read(imagem);//carrega a imagem real num buffer
            BufferedImage aux = new BufferedImage(100, 100, bi.getType());//cria um buffer auxiliar com o tamanho desejado
            Graphics2D g = aux.createGraphics();//pega a classe graphics do aux para edicao
            AffineTransform at = AffineTransform.getScaleInstance((double) 100 / bi.getWidth(), (double) 100 / bi.getHeight());//cria a transformacao
            g.drawRenderedImage(bi, at);//pinta e transforma a imagem real no auxiliar
            imgUser.setIcon(new ImageIcon(aux));//seta no jlabel
            // path = arq;

        } else {
        }

    }

    public void insereImagem(String login, RenderedImage image, FileInputStream fis) throws IOException {

        ByteArrayOutputStream bytesImg = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", bytesImg);

        bytesImg.flush();

        byte[] byteArray = bytesImg.toByteArray();
        bytesImg.close();
        try {
            //Statement stmt = (Statement) Conexao.conn.createStatement();

            PreparedStatement pstmt = (PreparedStatement) Conexao.conn.prepareStatement("INSERT INTO dataserverreligadora.imagem (login,foto) VALUES (?,?)");

            pstmt.setString(1, login);
            pstmt.setBytes(2, byteArray);
            pstmt.executeUpdate();
            pstmt.close();
            //  String sql = "INSERT INTO imagem (login,foto) VALUES('" + login + "','" + image + "')";

            // stmt.execute(sql);

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public File capturaImagem(int cod) throws IOException {

        File image = null;
        Blob blob = null;
        InputStream bin = null;
        FileOutputStream bout = null;
        byte[] bbuf = new byte[1024];
        int bytesRead = 0;
        BufferedImage img = null;

        String sql = "SELECT foto FROM dataserverreligadora.imagem WHERE id = " + cod;

        try {

            Statement stm = (Statement) Conexao.conn.createStatement();
            ResultSet rset = (ResultSet) stm.executeQuery(sql);

            //  PreparedStatement pstmt = (PreparedStatement) Conexao.conn.prepareStatement("SELECT foto FROM dataserverreligadora.imagem WHERE id = "+cod+"");

            //System.out.println(pstmt);
            //pstmt.setInt(0, cod); //Recuperando o id 20, só a título de exemplo

            //  ResultSet rs = (ResultSet) pstmt.execute(pstmt);


            if (rset.next()) {
                // recuperamos o array de bytes convertendo-o numa BufferedImage (img)...  
                //       img = ImageIO.read(new ByteArrayInputStream(rs.getBytes("Imagem_Img"))); 
                img = ImageIO.read(new ByteArrayInputStream(rset.getBytes("foto")));
                //  ImageIcon icon = new ImageIcon(img.getScaledInstance(img.getWidth(), img.getHeight(), 10000));
                imgUser = new JLabel(new ImageIcon(img.getSubimage(cod, cod, cod, cod)));

            }
//
//			blob = (Blob) rset.getBlob("foto");  
//			bin = blob.getBinaryStream();  
//			bout = new FileOutputStream("teste.jpg");  
//			
//			
//			while ((bytesRead = bin.read(bbuf)) != -1) {  
//			     bout.write(bbuf, 0, bytesRead);  
//			}  

        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }

        //image = new File("teste.jpg");

//                File img = new File("C:\\..\\image.jpg");
//BufferedImage bufferedImage = ImageIO.read(img);
//ImageIcon imageIcon = new ImageIcon(bufferedImage);
//                
//                try{
//                      // BufferedImage fundo = ImageIO.read(bin);
//              ImageIcon icon = new ImageIcon(img.getScaledInstance(img.getWidth(), img.getHeight(), 10000));
//              imgUser.setIcon(icon);
//                }catch(NullPointerException ne){
//                    System.out.println(ne);
//                }

        return image;




    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {


                //new frm_Usuarios(new conectDB("localhost", "dpaper", "root", "123456")).setVisible(true);
                new FormAlteraUsuario(null).setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_cadastrar;
    private javax.swing.JButton btn_cancelar1;
    private javax.swing.JComboBox cbx_login;
    private javax.swing.JComboBox cbx_tipoUser;
    private javax.swing.JLabel imgUser;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPasswordField jPasswordField_ConfirmaSenha;
    private javax.swing.JPasswordField jPasswordField_senha;
    private javax.swing.JCheckBox jcbx_alterar;
    private javax.swing.JCheckBox jcbx_consultar;
    private javax.swing.JCheckBox jcbx_excluir;
    private javax.swing.JCheckBox jcbx_incluir;
    private javax.swing.JCheckBox jcbx_todos;
    private javax.swing.JTextField txt_cod_user;
    public static javax.swing.JTextField txt_login;
    public static javax.swing.JTextField txt_nomeUsuario;
    // End of variables declaration//GEN-END:variables

    public void verificaCapsLock() {
        Toolkit tk = Toolkit.getDefaultToolkit();

        if (tk.getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
            //("Caps Lock está ativada");
        } else {
            //("Caps Lock não está ativada");
        }
    }

    class chamaPesquisa extends AbstractAction {

        public void actionPerformed(ActionEvent e) {

            String nome;

            try {

                nome = JOptionPane.showInputDialog(null, "Insira um nome para pesquisa ", "PESQUISA DE USUARIOS", JOptionPane.INFORMATION_MESSAGE);

                Statement stmt = null;
                ResultSet rs = null;

                // query que serÃ¡ executada
                // String sql = "SELECT * FROM projeto.usuario where cod_usuario = '"+ numero +"'";

                //  String sql = "SELECT c.cod_usuario, c.nome, c.login, c.email, tp.descricao FROM projeto.usuario c INNER JOIN projeto.tipo_usuario tp  ON tp.cod_tipo_usuario = c.cod_usuario WHERE c.cod_usuario = '" + valor + "'";
                String sql = "SELECT codUsuario, nomeUsuario, loginUsuario, emailUsuario,foneUsuario FROM dpaper.usuarios  Where  nomeUsuario  like '%" + nome + "%'";


                try {
                    // executa a query e guarda o resultado no RecordSet rs
                    stmt = (Statement) Conexao.conn.createStatement();
                    rs = (ResultSet) stmt.executeQuery(sql);

                    // enquanto houver dados no RS, retira os campos desejados (cod_usuario, nome e email) e mostra na tela
                    while (rs.next()) {

                        txt_cod_user.setText(rs.getString("codUsuario"));
                        txt_nomeUsuario.setText(rs.getString("nomeUsuario"));
                        txt_login.setText(rs.getString("loginUsuario"));


                    }

                } catch (SQLException er) {
                    //("erro listando usuarios: " + er.getMessage());
                } finally {
                    try {
                        // fecha o stmt e o rs
                        if (stmt != null) {
                            stmt.close();
                        }
                        if (rs != null) {
                            rs.close();
                        }
                    } catch (SQLException er) {
                        //("erro ao tentar fechar o stmt e o rs: " + er.getMessage());
                    }

                }

            } catch (NumberFormatException erro) {
                JOptionPane.showMessageDialog(null, "CAMPO EM BRANCO OU \n NUMEROS INVALIDOS", "PESQUISA DE USUARIOS", JOptionPane.INFORMATION_MESSAGE);
            } catch (ArrayIndexOutOfBoundsException erro) // se o cara deixa em branco
            {
                JOptionPane.showMessageDialog(null, "Digite Alguma Coisa! ", "PESQUISA DE USUARIOS", JOptionPane.INFORMATION_MESSAGE);
            }  // int coduser = Integer.parseInt(valor);


            //}
        }
    }

    public class ControlarEntradaTexto extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (Character.isLetter(str.charAt(0)) || str.equals("")) //(!Character.isDigit(evt.getKeyChar()) && !Character.isLetter(evt.getKeyChar()))
            {
                super.insertString(offs, str.toUpperCase(), a);
            }
        }
    }

    //LIMITA QUANTIDADE DE CARACTERES NO TEXTFIEL SELECIONADO
    public class MaxLengthTextDocument extends PlainDocument {
        //Armazena o número máximo de caracteres para o texto.

        int valor = 10;

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {
            if (str != null && (getLength() + str.length() < valor)) {
                super.insertString(offs, str, a);
            }
        }
    }

    public class tirarAcento extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String naoacentuado = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            naoacentuado = naoacentuado.replaceAll("[^a-zA-Z0-9_]", ""); // remove as sujeiras do processo acima.

            super.insertString(offs, naoacentuado, a);
        }
    }

    public class formatNome extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String naoacentuado = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            naoacentuado = naoacentuado.replaceAll("[^a-z A-Z ]", ""); // remove as sujeiras do processo acima.

            super.insertString(offs, naoacentuado, a);
        }
    }

    public class semCentencas extends PlainDocument {

        int valor = 10;

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String sentenca = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            sentenca = sentenca.replaceAll("[^a-z A-Z 0-9]", "");

            super.insertString(offs, sentenca, a);
        }
    }

    public class verificaEmail extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String sentenca = Normalizer.normalize(str.toUpperCase(), Normalizer.Form.NFD); // elimina os acentos.
            sentenca = sentenca.replaceAll("[^a-zA-Z-@.0-9_]", "");

            super.insertString(offs, sentenca, a);
        }
    }

    public class verificaSenha extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            if (str == null) {
                return;
            }

            String sentenca = Normalizer.normalize(str, Normalizer.Form.NFD); // elimina os acentos.
            sentenca = sentenca.replaceAll("[^a-zA-Z0-9]", "");

            super.insertString(offs, sentenca, a);
        }
    }

    public class ImagePreview extends JComponent
            implements PropertyChangeListener {

        ImageIcon thumbnail = null;
        File file = null;

        public ImagePreview(JFileChooser fc) {
            setPreferredSize(new Dimension(180, 50));
            fc.addPropertyChangeListener(this);
        }

        public void loadImage() {
            if (file == null) {
                thumbnail = null;
                return;
            }

            ImageIcon tmpIcon = new ImageIcon(file.getPath());
            if (tmpIcon != null) {
                if (tmpIcon.getIconWidth() > 180) {
                    thumbnail = new ImageIcon(tmpIcon.getImage().
                            getScaledInstance(180, -1,
                            Image.SCALE_DEFAULT));
                } else { //no need to miniaturize
                    thumbnail = tmpIcon;
                }
            }
        }

        public void propertyChange(PropertyChangeEvent e) {
            boolean update = false;
            String prop = e.getPropertyName();

            //If the directory changed, don't show an image.
            if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                file = null;
                update = true;

                //If a file became selected, find out which one.
            } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
                file = (File) e.getNewValue();
                update = true;
            }

            //Update the preview accordingly.
            if (update) {
                thumbnail = null;
                if (isShowing()) {
                    loadImage();
                    repaint();
                }
            }
        }

        protected void paintComponent(Graphics g) {
            if (thumbnail == null) {
                loadImage();
            }
            if (thumbnail != null) {
                int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
                int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;

                if (y < 0) {
                    y = 0;
                }

                if (x < 5) {
                    x = 5;
                }
                thumbnail.paintIcon(this, g, x, y);
            }
        }
    }
}
